import _ from '../libs/utils'
import store from '../stores/store'
import error from '../libs/errors'

export default {
  /**
   * 账号登录
   * 
   * account:账号
   * password:密码
   */
  async login(phone, password) {
    var ret = await _.ajax.post({
      url: '/api/auth/login',
      data: { phone: phone, password: password }
    });
    if (ret.stat === 'ok') {
      store.common.userInfo = ret.user;
      store.common.token = ret.session.token;
      _.cookie.set('token', ret.session.token);
    }
    return ret;
  },

  /**
   * 获取用户信息
   */
  async check() {
    var token = _.cookie.get('token');
    if(token == null || token == ''){
      return {stat:'tokenExpired', message:error.match('tokenExpired')}
    }
    var ret = await _.ajax.post({
      url: '/api/auth/check',
      data: { token: token }
    });
    if (ret.stat === 'ok') {
      store.common.userInfo = ret.ret;
    }
    return ret;
  },

  /**
   * 登出
   */
  async logout() {
    let token = _.cookie.get('token');
    var ret = await _.ajax.post({
      url: '/api/auth/logout',
      data: { token: token }
    });
    if (ret.stat === 'ok') {
      store.common.userInfo = null;
      _.cookie.remove('token');
    }
    return ret;
  }

}